package com.dineroquegastar.urule.aop;

import com.dineroquegastar.urule.constant.RespEnum;
import com.dineroquegastar.urule.exception.BusinessException;
import com.dineroquegastar.urule.utils.jackson.JsonJacksonUtil;
import com.dineroquegastar.urule.vo.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * 异常拦截器
 *
 * @author liuhai
 * @date 2021/03/28
 */
@ControllerAdvice
@Slf4j
public class ExceptionAdvice {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public ResponseVo exceptionHandler(Exception e, HttpServletRequest request) {
        log.error("控制层接口抛出异常，URL={}，异常信息={}", request.getRequestURI(), e.getMessage(), e);

        ResponseVo responseVo = getRespByException(e);
        log.error("[异常拦截] responseVo={}", JsonJacksonUtil.toJson(responseVo));
        return responseVo;
    }

    private ResponseVo getRespByException(Exception exception) {
        log.error("getRespByException:{}", exception.getMessage(), exception);
        if (exception instanceof BusinessException) {
            BusinessException businessException = BusinessException.class.cast(exception);
            return ResponseVo.fail(businessException.getCode(), businessException.getMessage());
        } else {
            return ResponseVo.fail(RespEnum.SYS_ERR);
        }
    }
}
